package com.cjym.GateWay.util;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 获取IP及ip归属地方法
 *
 * @author cjym
 */
public class IpUtils {
    public static String getIpAddr(HttpServletRequest request) {
        String ip = null;
        try {
            ip = request.getHeader("x-forwarded-for");
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        return ip;
    }

//    public static IpAddressVo getIpAddress(String ip)  {
//        try {
//            CloseableHttpClient httpClient = HttpClients.createDefault();
//            String url = "http://whois.pconline.com.cn/ipJson.jsp?ip=" + ip + "&json=true";
//            HttpGet httpGet = new HttpGet(url);
//            httpGet.setHeader("Content-Type", "application/json");
//            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
//                    .setSocketTimeout(5000).build();
//            httpGet.setConfig(requestConfig);
//            CloseableHttpResponse response = httpClient.execute(httpGet);
//            String result = EntityUtils.toString(response.getEntity(), "utf-8");
//            response.close();
//            response.close();
//            httpClient.close();
//            return JSONObject.parseObject(result, IpAddressVo.class);
//        }catch (Exception e){
//            IpAddressVo ipAddressVo=new IpAddressVo();
//            ipAddressVo.setIp(ip);
//            ipAddressVo.setErr("获取失败");
//            ipAddressVo.setCityCode("-1");
//            ipAddressVo.setAddr("ERROR");
//            return ipAddressVo;
//        }
//    }

    public static String getHostName()
    {
        try
        {
            return InetAddress.getLocalHost().getHostName();
        }
        catch (UnknownHostException e)
        {
        }
        return "未知";
    }

    public static String getHostIp()
    {
        try
        {
            return InetAddress.getLocalHost().getHostAddress();
        }
        catch (UnknownHostException e)
        {
        }
        return "127.0.0.1";
    }

}

